// pages/order-detail/order-detail.js
import { orderApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { formatPrice, formatDate, ORDER_STATUS_TEXT, PAY_METHOD_TEXT } from '../../utils/format.js'

const app = getApp()

Page({
  data: {
    loading: true,
    orderId: null,
    order: null,
    orderDetails: []
  },

  onLoad(options) {
    const { id } = options
    this.setData({
      orderId: id
    })
    
    this.loadOrderDetail()
  },

  onShow() {
    // 每次显示时重新加载订单详情
    this.loadOrderDetail()
  },

  onPullDownRefresh() {
    this.loadOrderDetail()
  },

  // 加载订单详情
  async loadOrderDetail() {
    if (!checkLoginAndRedirect()) {
      this.setData({ loading: false })
      return
    }

    try {
      this.setData({ loading: true })
      
      const res = await orderApi.getDetail(this.data.orderId)
      
      if (res.code === 1) {
        this.setData({
          order: res.data,
          orderDetails: res.data.orderDetailList || []
        })
        
        // 设置导航栏标题
        wx.setNavigationBarTitle({
          title: `订单详情`
        })
      }
    } catch (error) {
      console.error('加载订单详情失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
    }
  },

  // 取消订单
  async cancelOrder() {
    if (!this.data.order) return
    
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '取消中...' })
            
            const cancelRes = await orderApi.cancel(this.data.orderId)
            
            if (cancelRes.code === 1) {
              wx.showToast({
                title: '订单已取消',
                icon: 'success'
              })
              // 重新加载订单详情
              this.loadOrderDetail()
            } else {
              throw new Error(cancelRes.msg || '取消失败')
            }
          } catch (error) {
            console.error('取消订单失败:', error)
            wx.showToast({
              title: error.message || '取消失败',
              icon: 'none'
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 催单
  async remindOrder() {
    try {
      wx.showLoading({ title: '催单中...' })
      
      const res = await orderApi.reminder(this.data.orderId)
      
      if (res.code === 1) {
        wx.showToast({
          title: '催单成功',
          icon: 'success'
        })
      } else {
        throw new Error(res.msg || '催单失败')
      }
    } catch (error) {
      console.error('催单失败:', error)
      wx.showToast({
        title: error.message || '催单失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 再来一单
  async repeatOrder() {
    try {
      wx.showLoading({ title: '处理中...' })
      
      const res = await orderApi.repetition(this.data.orderId)
      
      if (res.code === 1) {
        wx.showToast({
          title: '已加入购物车',
          icon: 'success'
        })
        
        // 跳转到购物车
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/cart/cart'
          })
        }, 1500)
      } else {
        throw new Error(res.msg || '操作失败')
      }
    } catch (error) {
      console.error('再来一单失败:', error)
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 支付订单
  async payOrder() {
    try {
      wx.showLoading({ title: '支付中...' })
      
      const res = await orderApi.payment({
        orderNumber: this.data.order.number,
        payMethod: this.data.order.payMethod
      })
      
      if (res.code === 1) {
        // 调用微信支付
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.packageStr,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: () => {
            wx.showToast({
              title: '支付成功',
              icon: 'success'
            })
            // 重新加载订单详情
            this.loadOrderDetail()
          },
          fail: (error) => {
            console.error('支付失败:', error)
            wx.showToast({
              title: '支付失败',
              icon: 'none'
            })
          }
        })
      } else {
        throw new Error(res.msg || '支付失败')
      }
    } catch (error) {
      console.error('支付订单失败:', error)
      wx.showToast({
        title: error.message || '支付失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567',
      confirmText: '拨打',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567'
          })
        }
      }
    })
  },

  // 格式化订单状态
  formatOrderStatus(status) {
    return ORDER_STATUS_TEXT[status] || '未知状态'
  },

  // 格式化支付方式
  formatPayMethod(method) {
    return PAY_METHOD_TEXT[method] || '未知方式'
  },

  // 格式化时间
  formatTime(time) {
    return formatDate(time, 'YYYY-MM-DD HH:mm:ss')
  }
})